package com.utils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.crmeb.core.config.MybatisPlusConfig;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.utils.TableNameUtil;
import com.zbkj.crmeb.category.service.CategoryService;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.handler.orderproduct.OrderProductInterface;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.service.*;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.constants.Constants;
import com.zbkj.crmeb.chant.dto.ChannelDiscountDTO;
import com.zbkj.crmeb.chant.model.ChannelActivity;
import com.zbkj.crmeb.chant.request.ActivityDetailsRequest;
import com.zbkj.crmeb.chant.request.ChannelDiscountRequest;
import com.zbkj.crmeb.chant.response.PickingProductResponse;
import com.zbkj.crmeb.chant.service.ChannelActivityService;
import com.zbkj.crmeb.chant.service.ChannelDiscountService;
import com.zbkj.crmeb.chant.vo.ChannelProductVo;
import com.zbkj.crmeb.export.vo.ProductExcelVo;
import com.zbkj.crmeb.member.model.StoreProductLabel;
import com.zbkj.crmeb.member.service.IStoreProductLabelService;
import com.zbkj.crmeb.store.response.StoreProductApiResponse;
import com.zbkj.crmeb.system.model.SystemConfig;
import com.zbkj.crmeb.system.service.SystemAdminService;
import com.zbkj.crmeb.system.service.SystemConfigService;

import cn.hutool.core.util.ObjectUtil;

/**
 * 商品主信息和商品详情组合
 * @author daigb
 * @date:  2022-05-07 18:56
 */
@Service
@Slf4j
public class ProductConvertUtil {
    @Autowired
    private StoreProductDescriptionService storeProductDescriptionService;
    @Autowired
	@Lazy
	private StoreProductMerService storeProductMerService;
    @Autowired
	private IStoreProductLabelService storeProductLabelService;
    @Autowired
    private SystemAdminService systemAdminService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
	private ChannelActivityService channelActivityService;
	@Autowired
	private StoreProductGroupActivityService storeProductGroupActivityService;
	@Autowired
	private ChannelGroupBookingService channelGroupBookingService;
    @Autowired
    private ChannelDiscountService channelDiscountService;
	@Autowired
	private StoreBrandService storeBrandService;
	@Autowired
	private ICategoryMatchService categoryMatchService;

	private final static ExecutorService executorService = ThreadPoolUtils.getThread();
    
    /**
     * ids 可为空
     * @author daigb
     * @date:  2022-05-07 19:01
     */
    public void convertProduct(List<StoreProduct> products) {
    	if(CollectionUtils.isEmpty(products)) {
    		return;
    	}
    	List<Integer> ids = new ArrayList<>();
    	Map<Integer, StoreProduct> map = new HashMap<>();
    	// 获取商品id
    	for(StoreProduct product : products) {
    		int id = product.getId();
    		ids.add(id);
    		map.put(id, product);
    	}
    	// 查询商品详情
    	List<StoreProductDescription> storeProductDescriptions = storeProductDescriptionService.list(Wrappers.<StoreProductDescription>lambdaQuery()
        		.in(StoreProductDescription :: getProductId, ids)
        		);
    	Integer merId = systemAdminService.getAdminMerId();
		// 商户商品表
    	List<StoreProductMer> productMerList = null != merId ? storeProductMerService.list(Wrappers.<StoreProductMer>lambdaQuery()
				.in(StoreProductMer :: getProductId, ids)) : new ArrayList<>();
    	Map<Integer,StoreProductMer> productMerMap = productMerList.stream().collect(Collectors.toMap(StoreProductMer::getProductId,storeProductMer -> storeProductMer));
    	Map<Integer,String> labelMap = new HashMap<>();
    	if (CollectionUtils.isNotEmpty(productMerList)){
    		List<Integer> labelIds = productMerList.stream().map(StoreProductMer::getLabelId).filter(Objects::nonNull).collect(Collectors.toList());
    		if (CollectionUtils.isNotEmpty(labelIds)){
				List<StoreProductLabel> productLabelList = storeProductLabelService.list(Wrappers.<StoreProductLabel>lambdaQuery()
						.in(StoreProductLabel::getId,labelIds));
				labelMap = productLabelList.stream().collect(Collectors.toMap(StoreProductLabel::getId,StoreProductLabel::getLabelIconUrl));
			}
		}
    	//查询限时活动
		ActivityDetailsRequest detailsRequest = new ActivityDetailsRequest();
		detailsRequest.setMerId(merId);
		detailsRequest.setEventTimeType(2);
		detailsRequest.setCurrentTime(new Date());
		detailsRequest.setProductIdList(ids);
		//获取限制购买次数的活动及商品
		List<ChannelActivity> activityList = channelActivityService.getActivityByProduct(detailsRequest);
		Map<Integer,ChannelActivity> activityMap = activityList.stream().collect(Collectors.toMap(ChannelActivity::getProductId,channelActivity -> channelActivity,(c1,c2) ->{
			if (c1.getStartTime().before(c2.getStartTime())){
				return c1;
			}else {
				return c2;
			}
		}));
		
		// 商家进行中的拼团活动id
		List<Integer> merInProgressActivityIds = channelGroupBookingService.getInProgressActivityIds(merId);
		Map<Integer, BigDecimal> packagePriceMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(merInProgressActivityIds)){
			//获取拼团活动商品价格
			List<StoreProductGroupActivity> productGroupActivities = storeProductGroupActivityService.list(Wrappers.<StoreProductGroupActivity>lambdaQuery()
					.in(StoreProductGroupActivity::getActivityId, merInProgressActivityIds)
					.in(StoreProductGroupActivity::getProductId, ids));
			if (Objects.nonNull(productGroupActivities)){
				packagePriceMap = productGroupActivities.stream().collect(Collectors.toMap(StoreProductGroupActivity::getProductId, StoreProductGroupActivity::getPackagePrice, (v1, v2) -> {
					if (v1.compareTo(v2) > 0) {
						return v2;
					} else {
						return v1;
					}
				}));
			}
		}

		// 查询商家满减送活动
		ChannelDiscountRequest channelDiscountRequest = new ChannelDiscountRequest();
		channelDiscountRequest.setState(1);
		channelDiscountRequest.setStatus(true);
		List<ChannelDiscountDTO> channelDiscountDTOs = channelDiscountService.listEntity(merId, channelDiscountRequest);

		// 配对商品详情
    	for(StoreProductDescription storeProductDescription : storeProductDescriptions) {
    		StoreProduct storeProduct = map.get(storeProductDescription.getProductId());
    		StoreProductMer storeProductMer = productMerMap.get(storeProductDescription.getProductId());
    		if(ObjectUtil.isNotNull(storeProduct)) {
    			storeProduct.setImage(storeProductDescription.getImage());
    			storeProduct.setSliderImage(storeProductDescription.getSliderImage());
    			storeProduct.setUnitName(storeProductDescription.getUnitName());
    			storeProduct.setComposition(storeProductDescription.getComposition());
    			storeProduct.setDimension(storeProductDescription.getDimension());
    			storeProduct.setVideo(storeProductDescription.getVideo());
    			storeProduct.setGwpp1(storeProductDescription.getGwpp1());
    			storeProduct.setGwmt1(storeProductDescription.getGwmt1());
    			storeProduct.setSp1(storeProductDescription.getSp1());
    			storeProduct.setSp(storeProductDescription.getSp());
    			storeProduct.setMt1(storeProductDescription.getMt1());
    			storeProduct.setMt(storeProductDescription.getMt());
    			storeProduct.setMx1(storeProductDescription.getMx1());
    			storeProduct.setSp2(storeProductDescription.getSp2());
    			storeProduct.setSp3(storeProductDescription.getSp3());
    			storeProduct.setWeight(storeProductDescription.getWeight());
    			storeProduct.setProductionPlace(storeProductDescription.getProductionPlace());
    			storeProduct.setWinery(storeProductDescription.getWinery());
    			storeProduct.setProductYear(storeProductDescription.getProductYear());
    			storeProduct.setGrapeVariety(storeProductDescription.getGrapeVariety());
    			storeProduct.setStoreInfo(storeProductDescription.getDescription());
				storeProduct.setProductInformation(storeProductDescription.getProductInformation());
				if (ObjectUtil.isNotNull(storeProductMer)){
					storeProduct.setLabelDisplayType(storeProductMer.getLabelDisplayType());
					storeProduct.setLabelId(storeProductMer.getLabelId());
					storeProduct.setLabelIconUrl(labelMap.get(storeProductMer.getLabelId()));
					storeProduct.setPddGoodsId(storeProductMer.getPddGoodsId());
					storeProduct.setDeliveryData(storeProductMer.getDeliveryData());
					storeProduct.setEarliestArrivalData(storeProductMer.getEarliestArrivalData());
					storeProduct.setSlowestArrivalData(storeProductMer.getSlowestArrivalData());
				}
				storeProduct.setActivityFlag(0);
				if (ObjectUtil.isNotNull(activityMap.get(storeProduct.getId()))){
					storeProduct.setActivityFlag(1);
					BigDecimal spikPrice = activityMap.get(storeProduct.getId()).getMinPrice();
					if (Objects.nonNull(spikPrice) && spikPrice.compareTo(BigDecimal.ZERO) > 0){
						storeProduct.setSpikePrice(spikPrice);
					}
				}
				storeProduct.setActivityGroupFlag(0);
				if (Objects.nonNull(packagePriceMap.get(storeProduct.getId()))){
					storeProduct.setActivityGroupFlag(1);
					BigDecimal packagePrice = packagePriceMap.get(storeProduct.getId());
					if (Objects.nonNull(packagePrice) && packagePrice.compareTo(BigDecimal.ZERO) > 0){
						storeProduct.setPackagePrice(packagePrice);
					}
				}
				// 满减送活动
				ChannelDiscountDTO channelDiscountDTO = channelDiscountService.checkGoods2ChannelDiscount(merId, storeProduct.getId(), channelDiscountDTOs);
				storeProduct.setChannelDiscountDescription(channelDiscountDTO.getDescription());
				storeProduct.setChannelDiscountGiftProductInfo(channelDiscountDTO.getGiftGoods());
    		}
    	}
    }

	/**
	 * ids 可为空
	 * @author daigb
	 * @date:  2022-05-07 19:01
	 */
	public void convertProductV2(List<StoreProduct> products,Integer merId) {
		if(CollectionUtils.isEmpty(products)) {
			return;
		}
		// 兜底查询用户Id
		if (Objects.isNull(merId)){
			merId = systemAdminService.getAdminMerId();
		}
		if (Objects.isNull(merId)){
			throw new CrmebException("商户号获取失败，请重新登录");
		}
		final Integer currMerId = merId;

		final List<Integer> ids = new ArrayList<>();
		Map<Integer, StoreProduct> map = new HashMap<>();
		// 获取商品id
		for(StoreProduct product : products) {
			int id = product.getId();
			ids.add(id);
			map.put(id, product);
		}
		// 查询商品详情
		List<StoreProductDescription> storeProductDescriptions = storeProductDescriptionService.list(Wrappers.<StoreProductDescription>lambdaQuery()
				.in(StoreProductDescription :: getProductId, ids)
		);
		if (CollectionUtils.isEmpty(storeProductDescriptions)){
			return;
		}

		Map<Integer,StoreProductMer> productMerMap = new HashMap<>();
		Map<Integer,String> labelMap = new HashMap<>();
		CompletableFuture[] completableFutures = new CompletableFuture[]{null,null, null,null};
		completableFutures[0] = CompletableFuture.runAsync(() -> {
			MybatisPlusConfig.tableNameMp.set(TableNameUtil.getProductMerName(String.valueOf(currMerId)));
			// 商户商品表
			List<StoreProductMer> productMerList = storeProductMerService.list(Wrappers.<StoreProductMer>lambdaQuery().in(StoreProductMer :: getProductId, ids));
			if (CollectionUtils.isNotEmpty(productMerList)){
				List<Integer> labelIds = new ArrayList<>();
				for (StoreProductMer storeProductMer : productMerList) {
					productMerMap.put(storeProductMer.getProductId(), storeProductMer);
					if (Objects.nonNull(storeProductMer.getLabelId())){
						labelIds.add(storeProductMer.getLabelId());
					}
				}
				if (CollectionUtils.isNotEmpty(labelIds)){
					List<StoreProductLabel> productLabelList = storeProductLabelService.list(Wrappers.<StoreProductLabel>lambdaQuery()
							.in(StoreProductLabel::getId,labelIds));
					if (CollectionUtils.isNotEmpty(productLabelList)){
						labelMap.putAll(productLabelList.stream().collect(Collectors.toMap(StoreProductLabel::getId,StoreProductLabel::getLabelIconUrl)));
					}
				}
			}
		}, executorService);

		//查询限时活动
		final Map<Integer,ChannelActivity> activityMap = new HashMap<>();
		completableFutures[1] = CompletableFuture.runAsync(() -> {
			activityMap.putAll(getActivityDetailMap(currMerId,ids));
		});


		// 商家进行中的拼团活动id
		final Map<Integer, BigDecimal> packagePriceMap = new HashMap<>();
		completableFutures[2] = CompletableFuture.runAsync(() -> {
			packagePriceMap.putAll( getPackagePriceMap(currMerId,ids));
		});

		// 查询商家满减送活动
		final List<ChannelDiscountDTO> channelDiscountDTOs = new ArrayList<>();
		completableFutures[3] = CompletableFuture.runAsync(() -> {
			List<ChannelDiscountDTO> channelDiscountDTOS = getChannelDisCountDTO(currMerId);
			if (CollectionUtils.isNotEmpty(channelDiscountDTOS)){
				channelDiscountDTOs.addAll(channelDiscountDTOS);
			}
		});
		// 等待执行完
		CompletableFuture.allOf(completableFutures).join();

		// 配对商品详情
		for(StoreProductDescription storeProductDescription : storeProductDescriptions) {
			StoreProduct storeProduct = map.get(storeProductDescription.getProductId());
			if (null == storeProduct){
				continue;
			}
			storeProduct.setImage(storeProductDescription.getImage());
			storeProduct.setSliderImage(storeProductDescription.getSliderImage());
			storeProduct.setUnitName(storeProductDescription.getUnitName());
			storeProduct.setComposition(storeProductDescription.getComposition());
			storeProduct.setDimension(storeProductDescription.getDimension());
			storeProduct.setVideo(storeProductDescription.getVideo());
			storeProduct.setGwpp1(storeProductDescription.getGwpp1());
			storeProduct.setGwmt1(storeProductDescription.getGwmt1());
			storeProduct.setSp1(storeProductDescription.getSp1());
			storeProduct.setSp(storeProductDescription.getSp());
			storeProduct.setMt1(storeProductDescription.getMt1());
			storeProduct.setMt(storeProductDescription.getMt());
			storeProduct.setMx1(storeProductDescription.getMx1());
			storeProduct.setSp2(storeProductDescription.getSp2());
			storeProduct.setSp3(storeProductDescription.getSp3());
			storeProduct.setWeight(storeProductDescription.getWeight());
			storeProduct.setProductionPlace(storeProductDescription.getProductionPlace());
			storeProduct.setWinery(storeProductDescription.getWinery());
			storeProduct.setProductYear(storeProductDescription.getProductYear());
			storeProduct.setGrapeVariety(storeProductDescription.getGrapeVariety());
			storeProduct.setStoreInfo(storeProductDescription.getDescription());
			storeProduct.setProductInformation(storeProductDescription.getProductInformation());

			StoreProductMer storeProductMer = productMerMap.get(storeProductDescription.getProductId());
			if (ObjectUtil.isNotNull(storeProductMer)){
				storeProduct.setLabelDisplayType(storeProductMer.getLabelDisplayType());
				storeProduct.setLabelId(storeProductMer.getLabelId());
				storeProduct.setLabelIconUrl(labelMap.get(storeProductMer.getLabelId()));
				storeProduct.setPddGoodsId(storeProductMer.getPddGoodsId());
				storeProduct.setDeliveryData(storeProductMer.getDeliveryData());
				storeProduct.setEarliestArrivalData(storeProductMer.getEarliestArrivalData());
				storeProduct.setSlowestArrivalData(storeProductMer.getSlowestArrivalData());
			}
			storeProduct.setActivityFlag(0);
			if (ObjectUtil.isNotNull(activityMap.get(storeProduct.getId()))){
				storeProduct.setActivityFlag(1);
				BigDecimal spikPrice = activityMap.get(storeProduct.getId()).getMinPrice();
				if (Objects.nonNull(spikPrice) && spikPrice.compareTo(BigDecimal.ZERO) > 0){
					storeProduct.setSpikePrice(spikPrice);
				}
			}
			storeProduct.setActivityGroupFlag(0);
			if (Objects.nonNull(packagePriceMap.get(storeProduct.getId()))){
				storeProduct.setActivityGroupFlag(1);
				BigDecimal packagePrice = packagePriceMap.get(storeProduct.getId());
				if (Objects.nonNull(packagePrice) && packagePrice.compareTo(BigDecimal.ZERO) > 0){
					storeProduct.setPackagePrice(packagePrice);
				}
			}
			// 满减送活动
			ChannelDiscountDTO channelDiscountDTO = channelDiscountService.checkGoods2ChannelDiscount(merId, storeProduct.getId(), channelDiscountDTOs);
			storeProduct.setChannelDiscountDescription(channelDiscountDTO.getDescription());
			storeProduct.setChannelDiscountGiftProductInfo(channelDiscountDTO.getGiftGoods());
		}
	}

	/**
	 * ids 可为空
	 * @author daigb
	 * @date:  2022-05-07 19:01
	 */
	public void convertProductV3(List<StoreProduct> products, Integer leaderId) {
		if(CollectionUtils.isEmpty(products)) {
			return;
		}
		List<Integer> ids = new ArrayList<>();
		Map<Integer, StoreProduct> map = new HashMap<>();
		// 获取商品id
		for(StoreProduct product : products) {
			int id = product.getId();
			ids.add(id);
			map.put(id, product);
		}
		// 查询商品详情
		List<StoreProductDescription> storeProductDescriptions = storeProductDescriptionService.list(Wrappers.<StoreProductDescription>lambdaQuery()
				.in(StoreProductDescription :: getProductId, ids)
		);
		Integer merId = systemAdminService.getAdminMerId();
		// 商户商品表
		List<StoreProductMer> productMerList = null != merId ? storeProductMerService.list(Wrappers.<StoreProductMer>lambdaQuery()
				.in(StoreProductMer :: getProductId, ids)) : new ArrayList<>();
		Map<Integer,StoreProductMer> productMerMap = productMerList.stream().collect(Collectors.toMap(StoreProductMer::getProductId,storeProductMer -> storeProductMer));
		Map<Integer,String> labelMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(productMerList)){
			List<Integer> labelIds = productMerList.stream().map(StoreProductMer::getLabelId).filter(Objects::nonNull).collect(Collectors.toList());
			if (CollectionUtils.isNotEmpty(labelIds)){
				List<StoreProductLabel> productLabelList = storeProductLabelService.list(Wrappers.<StoreProductLabel>lambdaQuery()
						.in(StoreProductLabel::getId,labelIds));
				labelMap = productLabelList.stream().collect(Collectors.toMap(StoreProductLabel::getId,StoreProductLabel::getLabelIconUrl));
			}
		}
		//查询限时活动
		ActivityDetailsRequest detailsRequest = new ActivityDetailsRequest();
		detailsRequest.setMerId(merId);
		detailsRequest.setEventTimeType(2);
		detailsRequest.setCurrentTime(new Date());
		detailsRequest.setProductIdList(ids);
		//获取限制购买次数的活动及商品
		List<ChannelActivity> activityList = channelActivityService.getActivityByProduct(detailsRequest);
		log.info("查询限时活动:{}", JSONObject.toJSONString(activityList));
		Map<Integer,ChannelActivity> activityMap = activityList.stream().collect(Collectors.toMap(ChannelActivity::getProductId,channelActivity -> channelActivity,(c1,c2) ->{
			if (c1.getStartTime().before(c2.getStartTime())){
				return c1;
			}else {
				return c2;
			}
		}));

		// 商家进行中的拼团活动id
		List<Integer> merInProgressActivityIds = channelGroupBookingService.getInProgressActivityIdsAndLeaderId(merId,leaderId);
		Map<Integer, BigDecimal> packagePriceMap = new HashMap<>();
		if (CollectionUtils.isNotEmpty(merInProgressActivityIds)){
			//获取拼团活动商品价格
			List<StoreProductGroupActivity> productGroupActivities = storeProductGroupActivityService.list(Wrappers.<StoreProductGroupActivity>lambdaQuery()
					.in(StoreProductGroupActivity::getActivityId, merInProgressActivityIds)
					.in(StoreProductGroupActivity::getProductId, ids));
			if (Objects.nonNull(productGroupActivities)){
				packagePriceMap = productGroupActivities.stream().collect(Collectors.toMap(StoreProductGroupActivity::getProductId, StoreProductGroupActivity::getPackagePrice, (v1, v2) -> {
					if (v1.compareTo(v2) > 0) {
						return v2;
					} else {
						return v1;
					}
				}));
			}
		}

		// 查询商家满减送活动
		ChannelDiscountRequest channelDiscountRequest = new ChannelDiscountRequest();
		channelDiscountRequest.setState(1);
		channelDiscountRequest.setStatus(true);
		List<ChannelDiscountDTO> channelDiscountDTOs = channelDiscountService.listEntity(merId, channelDiscountRequest);

		// 配对商品详情
		for(StoreProductDescription storeProductDescription : storeProductDescriptions) {
			StoreProduct storeProduct = map.get(storeProductDescription.getProductId());
			StoreProductMer storeProductMer = productMerMap.get(storeProductDescription.getProductId());
			if(ObjectUtil.isNotNull(storeProduct)) {
				storeProduct.setImage(storeProductDescription.getImage());
				storeProduct.setSliderImage(storeProductDescription.getSliderImage());
				storeProduct.setUnitName(storeProductDescription.getUnitName());
				storeProduct.setComposition(storeProductDescription.getComposition());
				storeProduct.setDimension(storeProductDescription.getDimension());
				storeProduct.setVideo(storeProductDescription.getVideo());
				storeProduct.setGwpp1(storeProductDescription.getGwpp1());
				storeProduct.setGwmt1(storeProductDescription.getGwmt1());
				storeProduct.setSp1(storeProductDescription.getSp1());
				storeProduct.setSp(storeProductDescription.getSp());
				storeProduct.setMt1(storeProductDescription.getMt1());
				storeProduct.setMt(storeProductDescription.getMt());
				storeProduct.setMx1(storeProductDescription.getMx1());
				storeProduct.setSp2(storeProductDescription.getSp2());
				storeProduct.setSp3(storeProductDescription.getSp3());
				storeProduct.setWeight(storeProductDescription.getWeight());
				storeProduct.setProductionPlace(storeProductDescription.getProductionPlace());
				storeProduct.setWinery(storeProductDescription.getWinery());
				storeProduct.setProductYear(storeProductDescription.getProductYear());
				storeProduct.setGrapeVariety(storeProductDescription.getGrapeVariety());
				storeProduct.setStoreInfo(storeProductDescription.getDescription());
				storeProduct.setProductInformation(storeProductDescription.getProductInformation());
				if (ObjectUtil.isNotNull(storeProductMer)){
					storeProduct.setLabelDisplayType(storeProductMer.getLabelDisplayType());
					storeProduct.setLabelId(storeProductMer.getLabelId());
					storeProduct.setLabelIconUrl(labelMap.get(storeProductMer.getLabelId()));
					storeProduct.setPddGoodsId(storeProductMer.getPddGoodsId());
					storeProduct.setDeliveryData(storeProductMer.getDeliveryData());
					storeProduct.setEarliestArrivalData(storeProductMer.getEarliestArrivalData());
					storeProduct.setSlowestArrivalData(storeProductMer.getSlowestArrivalData());
				}
				storeProduct.setActivityFlag(0);
				if (ObjectUtil.isNotNull(activityMap.get(storeProduct.getId()))){
					log.info("查询限时活动详情:{}", JSONObject.toJSONString(activityMap.get(storeProduct.getId())));
					storeProduct.setActivityFlag(1);
					BigDecimal spikPrice = activityMap.get(storeProduct.getId()).getMinPrice();
					if (Objects.nonNull(spikPrice) && spikPrice.compareTo(BigDecimal.ZERO) > 0){
						storeProduct.setSpikePrice(spikPrice);
					}
				}
				storeProduct.setActivityGroupFlag(0);
				if (Objects.nonNull(packagePriceMap.get(storeProduct.getId()))){
					storeProduct.setActivityGroupFlag(1);
					BigDecimal packagePrice = packagePriceMap.get(storeProduct.getId());
					if (Objects.nonNull(packagePrice) && packagePrice.compareTo(BigDecimal.ZERO) > 0){
						storeProduct.setPackagePrice(packagePrice);
					}
				}
				// 满减送活动
				ChannelDiscountDTO channelDiscountDTO = channelDiscountService.checkGoods2ChannelDiscount(merId, storeProduct.getId(), channelDiscountDTOs);
				storeProduct.setChannelDiscountDescription(channelDiscountDTO.getDescription());
				storeProduct.setChannelDiscountGiftProductInfo(channelDiscountDTO.getGiftGoods());
			}
		}
	}

	/**
	 * 根据商家ID获取渠道折扣信息
	 *
	 * @param merId 商家ID，用于指定查询的商家
	 * @return 返回渠道折扣信息的列表，包含折扣详情的数据传输对象（DTO）
	 *
	 * 此方法通过构造查询请求并调用服务层方法来获取特定商家的渠道折扣信息。
	 * 查询请求中设置了状态为启用（状态码为1）且有效（状态为true）的折扣信息。
	 * 这样做的目的是为了确保返回的折扣信息是当前可用的，以供后续业务逻辑使用。
	 */
	private List<ChannelDiscountDTO> getChannelDisCountDTO(Integer merId) {
		ChannelDiscountRequest channelDiscountRequest = new ChannelDiscountRequest();
		channelDiscountRequest.setState(1);
		channelDiscountRequest.setStatus(true);
		return channelDiscountService.listEntity(merId, channelDiscountRequest);
	}

	/**
	 * 根据商家ID和商品ID列表，获取拼团活动的套餐价格映射。
	 * 对于每个商品ID，如果它参与了当前商家的拼团活动，那么返回该商品的拼团套餐价格。
	 * 如果一个商品参与了多个拼团活动，返回这些活动中的最低套餐价格。
	 *
	 * @param merId 商家ID，用于查询商家正在进行的拼团活动。
	 * @param ids 商品ID列表，用于查询这些商品是否参与了拼团活动。
	 * @return 返回一个映射，其中每个商品ID对应一个拼团套餐价格。如果某个商品没有参与拼团活动，或者商家没有进行中的拼团活动，则该商品ID不在映射中。
	 */
	private Map<Integer, BigDecimal> getPackagePriceMap(Integer merId, List<Integer> ids) {
		List<Integer> merInProgressActivityIds = channelGroupBookingService.getInProgressActivityIds(merId);
		if (CollectionUtils.isEmpty(merInProgressActivityIds)){
			return new HashMap<>();
		}
			//获取拼团活动商品价格
		List<StoreProductGroupActivity> productGroupActivities = storeProductGroupActivityService.list(Wrappers.<StoreProductGroupActivity>lambdaQuery()
				.in(StoreProductGroupActivity::getActivityId, merInProgressActivityIds)
				.in(StoreProductGroupActivity::getProductId, ids));
		if (CollectionUtils.isEmpty(productGroupActivities)){
			return new HashMap<>();
		}
		return productGroupActivities.stream().collect(Collectors.toMap(StoreProductGroupActivity::getProductId, StoreProductGroupActivity::getPackagePrice, (v1, v2) -> {
			if (v1.compareTo(v2) > 0) {
				return v2;
			} else {
				return v1;
			}
		}));
	}

	/**
	 * 根据商家ID和产品ID列表，获取活动详情的映射表。
	 * 映射表中的每个键是产品ID，对应的值是该产品的相关活动信息。
	 * 如果一个产品有多个活动，只选择开始时间最早的活动。
	 *
	 * @param merId 商家ID，用于筛选活动。
	 * @param ids 产品ID列表，用于查询这些产品对应的活动。
	 * @return 返回一个映射表，包含每个产品及其相关的活动信息。
	 */
	private Map<Integer, ChannelActivity> getActivityDetailMap(Integer merId, List<Integer> ids) {
		ActivityDetailsRequest detailsRequest = new ActivityDetailsRequest();
		detailsRequest.setMerId(merId);
		detailsRequest.setEventTimeType(2);
		detailsRequest.setCurrentTime(new Date());
		detailsRequest.setProductIdList(ids);
		//获取限制购买次数的活动及商品
		List<ChannelActivity> activityList = channelActivityService.getActivityByProduct(detailsRequest);
        return activityList.stream().collect(Collectors.toMap(ChannelActivity::getProductId, channelActivity -> channelActivity,(c1, c2) ->{
			if (c1.getStartTime().before(c2.getStartTime())){
				return c1;
			}else {
				return c2;
			}
		}));
	}

	public void convertProductExcel(List<ProductExcelVo> products) {
    	if(CollectionUtils.isEmpty(products)) {
    		return;
    	}
		List<Integer> productIdList = products.stream().map(ProductExcelVo::getId).distinct().collect(Collectors.toList());
    	// 查询商品详情
    	List<StoreProductDescription> storeProductDescriptions = storeProductDescriptionService.list(Wrappers.<StoreProductDescription>lambdaQuery()
    			.in(StoreProductDescription :: getProductId, productIdList)
    			);
		Map<Integer, StoreProductDescription> descriptionMap = storeProductDescriptions.stream().collect(Collectors.toMap(StoreProductDescription::getProductId, e -> e));
		for (ProductExcelVo storeProduct : products) {
			StoreProductDescription storeProductDescription = descriptionMap.get(storeProduct.getId());
			if(Objects.nonNull(storeProductDescription)){
				storeProduct.setImage(storeProductDescription.getImage());
				storeProduct.setSliderImage(storeProductDescription.getSliderImage());
				storeProduct.setUnitName(storeProductDescription.getUnitName());
				storeProduct.setComposition(storeProductDescription.getComposition());
				storeProduct.setDimension(storeProductDescription.getDimension());
				storeProduct.setStoreInfo(storeProductDescription.getDescription());
			}
		}
    }
    
    public void convertProductApi(List<StoreProductApiResponse> products) {
    	if(CollectionUtils.isEmpty(products)) {
    		return;
    	}
    	List<Integer> ids = new ArrayList<>();
    	Map<Integer, StoreProductApiResponse> map = new HashMap<>();
    	// 获取商品id
    	for(StoreProductApiResponse product : products) {
    		int id = product.getId();
    		ids.add(id);
    		map.put(id, product);
    	}
    	// 查询商品详情
    	List<StoreProductDescription> storeProductDescriptions = storeProductDescriptionService.list(Wrappers.<StoreProductDescription>lambdaQuery()
    			.in(StoreProductDescription :: getProductId, ids)
    			);
    	// 配对商品详情
    	for(StoreProductDescription storeProductDescription : storeProductDescriptions) {
    		StoreProductApiResponse storeProduct = map.get(storeProductDescription.getProductId());
    		if(ObjectUtil.isNotNull(storeProduct)) {
    			storeProduct.setImage(storeProductDescription.getImage());
    			storeProduct.setSliderImage(storeProductDescription.getSliderImage());
    			storeProduct.setUnitName(storeProductDescription.getUnitName());
    			storeProduct.setComposition(storeProductDescription.getComposition());
    			storeProduct.setDimension(storeProductDescription.getDimension());
    			storeProduct.setStoreInfo(storeProductDescription.getDescription());
    		}
    	}
    }
    
    /**
     * 只匹配主图片(商品列表场景)
     * @author daigb
     * @date:  2022-06-21 14:19
     */
    public void convertProductImage(List<StoreProduct> products) {
    	if(CollectionUtils.isEmpty(products)) {
    		return;
    	}
    	List<Integer> ids = new ArrayList<>();
    	Map<Integer, StoreProduct> map = new HashMap<>();
    	// 获取商品id
    	for(StoreProduct product : products) {
    		int id = product.getId();
    		ids.add(id);
    		map.put(id, product);
    	}
    	// 查询商品详情
    	List<StoreProductDescription> storeProductDescriptions = storeProductDescriptionService.list(Wrappers.<StoreProductDescription>lambdaQuery()
    			.in(StoreProductDescription :: getProductId, ids)
    			);
    	// 查询是否有拼多多开放权限
    	Map<Integer,StoreProductMer> productMerMap = new HashMap<>();
    	Integer merId = systemAdminService.getAdminMerId();
    	SystemConfig configProductDetail = systemConfigService.getMerchantCustomConfig(merId, Constants.CONFIG_PRODUCT_DETAIL);
    	boolean isPdd = null != configProductDetail && "1".equals(configProductDetail.getValue());
    	if(isPdd) {
    		// 商户商品表
    		List<StoreProductMer> productMerList = null != merId ? storeProductMerService.list(Wrappers.<StoreProductMer>lambdaQuery()
    				.in(StoreProductMer :: getProductId, ids)) : new ArrayList<>();
    		productMerMap = productMerList.stream().collect(Collectors.toMap(StoreProductMer::getProductId,storeProductMer -> storeProductMer));
    	}
    	// 配对商品详情
    	for(StoreProductDescription storeProductDescription : storeProductDescriptions) {
    		StoreProduct storeProduct = map.get(storeProductDescription.getProductId());
    		if(ObjectUtil.isNotNull(storeProduct)) {
    			storeProduct.setImage(storeProductDescription.getImage());
    			
    			// 拼多多商品属性
    			if(isPdd) {
    				StoreProductMer storeProductMer = productMerMap.get(storeProductDescription.getProductId());
    				if (ObjectUtil.isNotNull(storeProductMer)){
    					storeProduct.setPddGoodsId(storeProductMer.getPddGoodsId());
    				}
    			}
    		}
    	}
    	
    }

	/**
	 * 只匹配主图片(商品列表场景)
	 * @author daigb
	 * @date:  2022-06-21 14:19
	 */
	public void convertProductPickingImage(List<PickingProductResponse> products) {
		if(CollectionUtils.isEmpty(products)) {
			return;
		}
		List<Integer> productIdList = products.stream().map(PickingProductResponse::getProductId).collect(Collectors.toList());
		// 查询商品详情
		List<StoreProductDescription> storeProductDescriptions = storeProductDescriptionService.list(Wrappers.<StoreProductDescription>lambdaQuery()
				.in(StoreProductDescription :: getProductId, productIdList)
		);
		Map<Integer, StoreProductDescription> descriptionMap = storeProductDescriptions.stream().collect(Collectors.toMap(StoreProductDescription::getProductId, e -> e));
		// 配对商品详情
		for (PickingProductResponse storeProduct : products) {
			StoreProductDescription storeProductDescription = descriptionMap.get(storeProduct.getProductId());
			if(Objects.nonNull(storeProductDescription)){
				storeProduct.setImage(storeProductDescription.getImage());
				storeProduct.setSliderImage(storeProductDescription.getSliderImage());
			}
		}
	}
    
    /**
     * 只匹配主图片(商品列表场景)
     * @author daigb
     * @date:  2022-06-21 14:19
     */
    public void convertProductDraftImage(List<StoreProductDraft> products) {
    	if(CollectionUtils.isEmpty(products)) {
    		return;
    	}
    	List<Integer> ids = new ArrayList<>();
    	Map<Integer, StoreProductDraft> map = new HashMap<>();
    	// 获取商品id
    	for(StoreProductDraft product : products) {
    		int id = product.getId();
    		ids.add(id);
    		map.put(id, product);
    	}
    	// 查询商品详情
    	List<StoreProductDescription> storeProductDescriptions = storeProductDescriptionService.list(Wrappers.<StoreProductDescription>lambdaQuery()
    			.in(StoreProductDescription :: getProductId, ids)
    			);
    	// 配对商品详情
    	for(StoreProductDescription storeProductDescription : storeProductDescriptions) {
    		StoreProductDraft storeProduct = map.get(storeProductDescription.getProductId());
    		if(ObjectUtil.isNotNull(storeProduct)) {
    			storeProduct.setImage(storeProductDescription.getImage());
    		}
    	}
    }
    
    /**
     * 只匹配主图片(商品列表场景)
     * @author daigb
     * @date:  2022-06-21 14:19
     */
    public void convertProductVoImage(List<ChannelProductVo> products) {
    	if(CollectionUtils.isEmpty(products)) {
    		return;
    	}
    	List<Integer> ids = new ArrayList<>();
    	Map<Integer, ChannelProductVo> map = new HashMap<>();
    	// 获取商品id
    	for(ChannelProductVo product : products) {
    		int id = product.getId();
    		ids.add(id);
    		map.put(id, product);
    	}
    	// 查询商品详情
    	List<StoreProductDescription> storeProductDescriptions = storeProductDescriptionService.list(Wrappers.<StoreProductDescription>lambdaQuery()
    			.in(StoreProductDescription :: getProductId, ids)
    			);
    	// 配对商品详情
    	for(StoreProductDescription storeProductDescription : storeProductDescriptions) {
    		ChannelProductVo storeProduct = map.get(storeProductDescription.getProductId());
    		if(ObjectUtil.isNotNull(storeProduct)) {
    			storeProduct.setImage(storeProductDescription.getImage());
    		}
    	}
    }
    
    public void convertProduct(StoreProduct product) {
    	if(ObjectUtil.isNull(product)) {
    		return;
    	}
    	// 查询商品详情
    	StoreProductDescription storeProductDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
    			.eq(StoreProductDescription :: getProductId, product.getId())
    			.last("LIMIT 1")
    			);

		JSONObject jsonObject = OrderProductInterface.THREAD_LOCAL.get();
		// todo 兼容非servlet请求
		Integer merId = null;
		if (null != jsonObject && null != jsonObject.get("merId")){
			merId = jsonObject.getInteger("merId");
		}else {
			merId = systemAdminService.getAdminMerId();
		}
		// 商户商品表
		StoreProductMer storeProductMer = null != merId ? storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery()
				.eq(StoreProductMer :: getProductId, product.getId())) : null;
		StoreProductLabel storeProductLabel = new StoreProductLabel();
		if (ObjectUtil.isNotNull(storeProductMer)){
			storeProductLabel = storeProductLabelService.getById(storeProductMer.getLabelId());
		}

    	// 配对商品详情
		if(ObjectUtil.isNotNull(storeProductDescription)) {
			product.setImage(storeProductDescription.getImage());
			product.setSliderImage(storeProductDescription.getSliderImage());
			product.setUnitName(storeProductDescription.getUnitName());
			product.setComposition(storeProductDescription.getComposition());
			product.setDimension(storeProductDescription.getDimension());
			product.setVideo(storeProductDescription.getVideo());
			product.setGwpp1(storeProductDescription.getGwpp1());
			product.setGwmt1(storeProductDescription.getGwmt1());
			product.setSp1(storeProductDescription.getSp1());
			if (Objects.equals(storeProductDescription.getSp1(),"null")){
				product.setSp1("[]");
			}
			product.setSp(storeProductDescription.getSp());
			product.setMt1(storeProductDescription.getMt1());
			product.setMt(storeProductDescription.getMt());
			product.setMx1(storeProductDescription.getMx1());
			product.setSp2(storeProductDescription.getSp2());
			product.setSp3(storeProductDescription.getSp3());
			product.setWeight(storeProductDescription.getWeight());
			product.setProductionPlace(storeProductDescription.getProductionPlace());
			product.setWinery(storeProductDescription.getWinery());
			product.setProductYear(storeProductDescription.getProductYear());
			product.setGrapeVariety(storeProductDescription.getGrapeVariety());
			product.setStoreInfo(storeProductDescription.getDescription());
			product.setProductInformation(storeProductDescription.getProductInformation());
			if (ObjectUtil.isNotNull(storeProductMer) && ObjectUtil.isNotNull(storeProductLabel)){
				product.setLabelDisplayType(storeProductMer.getLabelDisplayType());
				product.setLabelIconUrl(storeProductLabel.getLabelIconUrl());
				product.setLabelId(storeProductMer.getLabelId());
			}

		}
    }

	public void assembledPlatInfo(List<StoreProductResponse> result) {
		if (CollectionUtils.isEmpty(result)){
			return;
		}
		List<Integer> brandIds = new ArrayList<>();
		List<Integer> categoryIds = new ArrayList<>();
		for (StoreProductResponse storeProduct : result) {
			brandIds.add(storeProduct.getBrandId());
			categoryIds.add(storeProduct.getCateId());
		}
		Map<Integer, StoreBrand> brandMap = getBrandMap(brandIds);
		Map<Integer, CategoryMatch> categoryMap = getCategoryMap(categoryIds);
		for (StoreProductResponse storeProduct : result) {
			if (MapUtils.isEmpty(brandMap) || !brandMap.containsKey(storeProduct.getBrandId())){
				continue;
			}
			StoreBrand storeBrand = brandMap.get(storeProduct.getBrandId());
			storeProduct.setByBrandId(storeBrand.getByBrandId());
			// {"byBrandZhName":"古驰","byBrandEnName":"Gucci"}
			storeProduct.setByBrandName(org.apache.commons.lang3.StringUtils.defaultString(storeBrand.getFeature("byBrandZhName"),storeBrand.getFeature("byBrandEnName")));

			if (MapUtils.isEmpty(categoryMap) || !categoryMap.containsKey(storeProduct.getCateId())){
				continue;
			}
			CategoryMatch categoryMatch = categoryMap.get(storeProduct.getCateId());
			storeProduct.setByCategoryId(categoryMatch.getByCategoryId());
			// {"byCategoryEnName":"swimsuit","byCategoryZhName":"泳装"}
			storeProduct.setByCategoryName(org.apache.commons.lang3.StringUtils.defaultString(categoryMatch.getFeature("byCategoryZhName"),categoryMatch.getFeature("byCategoryEnName")));
		}
	}

	private Map<Integer, CategoryMatch> getCategoryMap(List<Integer> categoryIds) {
		if (CollectionUtils.isEmpty(categoryIds)){
			return null;
		}
		List<CategoryMatch> categoryMatches = categoryMatchService.listByIds(categoryIds);
		if (CollectionUtils.isEmpty(categoryMatches)){
			return null;
		}
		return categoryMatches.stream().collect(Collectors.toMap(CategoryMatch::getId, v->v));
	}

	private Map<Integer, StoreBrand> getBrandMap(List<Integer> brandIds) {
		if (CollectionUtils.isEmpty(brandIds)){
			return null;
		}
		List<StoreBrand> storeBrands = storeBrandService.listByIds(brandIds);
		if (CollectionUtils.isEmpty(storeBrands)){
			return null;
		}
		return storeBrands.stream().collect(Collectors.toMap(StoreBrand::getId, v -> v));
	}
}
